package common

import (
	"database/sql"
	_ "github.com/bmizerany/pq"
	"sync"
)

var (
	pgsqlOnce sync.Once
	pgClient  *sql.DB
)

type Pgsql struct {
	conf *Config
}

func (s *Pgsql) Get() *sql.DB {
	pgsqlOnce.Do(func() {
		var err error
		pgClient, err = sql.Open("postgres", s.conf.Get().Pgsql.Master.Addr)
		if err != nil {
			panic(err)
		}
		err = pgClient.Ping()
		if err != nil {
			panic(err)
		}
		pgClient.SetMaxOpenConns(s.conf.Get().Pgsql.Master.MaxOpenConns)
		pgClient.SetMaxIdleConns(s.conf.Get().Pgsql.Master.MaxIdleConns)
	})
	return pgClient
}
